package LeetCode.exercise;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class LC_15 {
    public static void main(String[] args) {
        int[] nums = {-1,0,1,2,-1,-4};
        System.out.println(threeSum(nums));
    }
    public static List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        int i = 0, n = nums.length -1;
        List<List<Integer>> lists = new ArrayList<>();
        while (nums[i] <= 0 && i < n){
            int left = i + 1, right = n;
            while (left < right){
                int sum = nums[left] + nums[right];
                if(sum == -nums[i]){
                    lists.add(new ArrayList<Integer>(Arrays.asList(nums[i], nums[left], nums[right])));
                    while (left < right){
                        if(nums[left] != nums[left+1] && nums[right] != nums[right-1]) {
                            left++;
                            right--;
                            break;
                        }
                        if(nums[left] == nums[left+1]){
                            left++;
                        }
                        if(nums[right] == nums[right-1]){
                            right--;
                        }
                    }
                } else if(sum < -nums[i]){
                    left++;
                } else {
                    right--;
                }
            }
            i++;
            while (i < n && nums[i] == nums[i-1]){
                i++;
            }
        }
        return lists;
    }
}
